﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Xwork.SEO.WebSite.Controllers
{
    
    public class AccountController : SEOController
    {
        //
        // GET: /Account/
        [UserAuthorize]
        public ActionResult Index()
        {
            string s = db.Users.Where(p => p.Email.Equals("sdf", StringComparison.OrdinalIgnoreCase)).ToString();
            return View();
        }
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(string email, string password, bool? remember, string returnUrl)
        {

            HttpCookie cookie = new HttpCookie("username", email);
            cookie.Path = "/";
            cookie.Expires = DateTime.Now.AddDays(-1);
            if (remember.HasValue && remember.Value)
            {
                cookie.Expires = DateTime.Now.AddMonths(1);
            }
            Response.SetCookie(cookie);
            User user = db.Login(email, password);
            Session["user"] = user;
            return Json(new { url = returnUrl });
        }

        public ActionResult Reg()
        {
            return View();
        }

        public ActionResult CheckUserName(string email)
        {
            if(string.IsNullOrWhiteSpace(email))
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
            email = email.Trim();
            return Json(!db.Users.Any(p => p.Email == email), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult Reg(Models.RegModel model)
        {
            if (ModelState.IsValid)
            {
                if ((string)Session["vcode"] != model.Vcode)
                {
                    return Json(new { error = "验证码不正确" });
                }
                Session["user"] = db.Reg(model.Email, model.Password);
                db.SendValidateEmail(User.ID);
                return Json(new { url = Url.Action("validate", "account") });
            }
            return Json(new { error = "输入信息不正确" });
        }


        public ActionResult CheckVcode(string vcode)
        {
            return Json((string)Session["vcode"] == vcode, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Vcode()
        {
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            Random random = new Random();
            string code = random.Next(1000, 10000).ToString();
            Session["vcode"] = code;
            Bitmap image = new Bitmap((int)Math.Ceiling(code.Length * 14.0 + 10), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器   
                //清空图片背景色   
                g.Clear(Color.White);
                //画图片的干扰线   
                for (int i = 0; i < 10; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                Font font = new Font("Arial", 14, (FontStyle.Bold | FontStyle.Italic));
                Color color1 = Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
                Color color2 = Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
                float f = (float)(random.Next(35, 90));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
                 color1, color2, f, true);
                g.DrawString(code, font, brush, 3, 2);
                //画图片的前景干扰点   
                for (int i = 0; i < 150; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线   
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                //保存图片数据   
                //MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                //输出图片流   
                //return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
            return File(stream.ToArray(), "image/jpg");
        }

        public ActionResult Validate()
        {
            if (!IsLogin)
            {
                return RedirectToAction("login");
            }
            return View(this.User);
        }


        /// <summary>
        /// 验证返回
        /// </summary>
        /// <returns></returns>
        public ActionResult ValidateBack(string code)
        {
            //TODO 添加验证用户信息代码并返回验证结果页
            return View();
        }


        public ActionResult Logout()
        {
            Session.Abandon();
            return Redirect(Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : "/");
        }
    }
}
